<template>
  <div class="app-container">
    <el-row>
      <el-upload
        action="http://47.108.138.115:8080/mealUser/updateUserIcon"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :headers="myHeaders"
      >
        <div class="avatar">
          <el-avatar :size="200" :src="userInfo.avatar"></el-avatar>
          <i class="el-icon-edit-outline avatar-uploader-icon"></i>
        </div>
      </el-upload>
    </el-row>
    <el-row>
      <el-input v-model="tmpName" placeholder="请输入新用户名"></el-input>
    </el-row>
    <el-row>
      <el-button type="primary" @click="updateUser">
        保存
      </el-button>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "setting",
  data() {
    return {
      myHeaders: { satoken: this.$store.getters.token },
      userInfo: {
        id: 0,
        avatar: "",
        userAccount: ""
      },
      tmpName: undefined
    };
  },
  created() {
    this.userInfo.avatar = this.$store.getters.avatar;
    this.userInfo.id = this.$store.getters.id;
    this.userInfo.name = this.$store.getters.name;
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.userInfo.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isGIFJPG = file.type === "image/gif" || "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isGIFJPG) {
        this.$message.error("上传头像图片只能是 JPG 或 GIF 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isGIF && isLt2M;
    },
    updateUser() {
      this.loading = true;
      if (this.tmpName) {
        this.userInfo.userAccount = this.tmpName;
      }
      this.$store.dispatch("user/userUpdate", this.userInfo).then(() => {
        this.$router.push({
          path: "/dashboard"
        });
        this.loading = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
  margin-left: 20px;
  &:first-child {
    margin-top: 10px;
  }
  &:nth-child(2) {
    width: 200px;
  }
}
.avatar {
  position: relative;
  .avatar-uploader-icon {
    position: absolute;
    right: 0;
    bottom: 0;
    color: #409eff;
    font-size: 30px;
    font-weight: bold;
  }
}
</style>
